package com.huaxin.hxmoduleworkorder.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huaxin.hxmoduleworkorder.dto.ResponseResult;
import com.huaxin.hxmoduleworkorder.dto.request.InspectionOrderCreateReqDTO;
import com.huaxin.hxmoduleworkorder.dto.request.InspectionOrderPageListReqDTO;
import com.huaxin.hxmoduleworkorder.dto.request.InspectionOrderUpdateReqDTO;
import com.huaxin.hxmoduleworkorder.dto.response.GetInspectionOrderCustomerRespDTO;
import com.huaxin.hxmoduleworkorder.models.InspectionOrder;
import com.huaxin.hxmoduleworkorder.service.InspectionOrderCustomerService;
import com.huaxin.hxmoduleworkorder.service.InspectionOrderService;
import com.huaxin.hxmoduleworkorder.service.InspectionReportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@Tag(name = "巡查工单")
@RestController
@RequiredArgsConstructor
@RequestMapping("/v1/workorder/inspectionOrder")
public class InspectionOrderController {
    private final InspectionOrderService service;
    private final InspectionOrderCustomerService orderCustomerService;
    private final InspectionReportService reportService;

    @Operation(summary = "新增", description = "新增")
    @PostMapping("/create")
    public ResponseResult<InspectionOrder> create(@RequestBody InspectionOrderCreateReqDTO in) {
        return service.create(in);
    }

    @Operation(summary = "根据ID查询", description = "根据ID查询")
    @GetMapping("/get")
    public ResponseResult<InspectionOrder> get(@Parameter(description = "ID", name = "id") @RequestParam(name = "id", required = true) String id) {
        return service.get(id);
    }

    @Operation(summary = "更新", description = "更新")
    @PostMapping("/update")
    public ResponseResult<String> update(@RequestBody InspectionOrderUpdateReqDTO in) {
        return service.update(in);
    }

    @Operation(summary = "删除", description = "删除")
    @DeleteMapping("/{id}/delete")
    public ResponseResult<String> delete(@Parameter(description = "ID") @PathVariable String id) {
        return service.delete(id);
    }

    @Operation(summary = "获取分页列表", description = "获取分页列表")
    @PostMapping("/pageList")
    public ResponseResult<Page<InspectionOrder>> pageList(@RequestBody InspectionOrderPageListReqDTO in) {
        return service.pageList(in);
    }

    /**
     * 获取巡查任务关联客户信息
     *
     * @param id 工单ID
     * @return 工单关联客户信息
     */
    @Operation(summary = "获取巡查任务关联客户信息", description = "获取巡查任务关联客户信息")
    @PostMapping("/getInspectionOrderCustomer")
    public ResponseResult<Page<GetInspectionOrderCustomerRespDTO>> getInspectionOrderCustomer(@Parameter(description = "页码", name = "pageNum") @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                                                                              @Parameter(description = "页大小", name = "pageSize") @RequestParam(name = "pageSize", required = true) Integer pageSize,
                                                                                              @Parameter(description = "ID", name = "id") @RequestParam(name = "id", required = true) String id) {
        return orderCustomerService.pageList(pageNum, pageSize, id);
    }

    @Operation(summary = "判断工单是否存在（通过ID）", description = "判断工单是否存在（通过ID）")
    @GetMapping("/exist")
    public ResponseResult<Boolean> exist(@Parameter(description = "ID", name = "id") @RequestParam(name = "id", required = true) String id) {
        return service.exist(id);
    }

    @Operation(summary = "取消工单", description = "取消工单")
    @PutMapping("/{id}/cancel")
    public ResponseResult<Boolean> cancel(@Parameter(description = "ID", name = "id") @RequestParam(name = "id", required = true) @PathVariable String id) {
        return service.cancel(id);
    }

    @Operation(summary = "查询每个配电房关联的巡检项数量", description = "查询每个配电房关联的巡检项数量")
    @GetMapping("/countItemsByRoomIds")
    public ResponseResult<List<Map<String, Object>>> countItemsByRoomIds(@Parameter(description = "配电房ID列表", name = "roomIds") @RequestParam(name = "roomIds", required = true) List<String> roomIds,
                                                                         @Parameter(description = "巡检单ID", name = "inspectionOrderId") @RequestParam(name = "inspectionOrderId", required = true) String inspectionOrderId) {
        return service.countItemsByRoomIds(roomIds, inspectionOrderId);
    }

    @GetMapping("/downloadGenerateReport")
    @Operation(summary = "下载巡检报告", description = "下载巡检报告")
    public void downloadReport(@Parameter(description = "检查单ID", name = "inspectionId") @RequestParam(name = "inspectionId", required = true) String inspectionId,
                               @Parameter(description = "客户ID", name = "customerId") @RequestParam(name = "customerId", required = true) String customerId,
                               HttpServletResponse response) {
        byte[] pdfBytes = reportService.generateReport(inspectionId, customerId);

        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"inspection-report-" + inspectionId + ".pdf\"");

        try (ServletOutputStream out = response.getOutputStream()) {
            out.write(pdfBytes);
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException("PDF 下载失败", e);
        }
    }

    // 预览报告（直接浏览器打开）
    @GetMapping("/viewGenerateReport")
    @Operation(summary = "预览报告", description = "预览报告")
    public void viewReport(@Parameter(description = "检查单ID", name = "inspectionId") @RequestParam(name = "inspectionId", required = true) String inspectionId,
                           @Parameter(description = "客户ID", name = "customerId") @RequestParam(name = "customerId", required = true) String customerId,
                           HttpServletResponse response) {
        byte[] pdfBytes = reportService.generateReport(inspectionId, customerId);

        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline; filename=\"inspection-report-" + inspectionId + ".pdf\"");

        try (OutputStream out = response.getOutputStream()) {
            out.write(pdfBytes);
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException("PDF 查看失败", e);
        }
    }

    /**
     * 创建巡查任务-测试
     *
     * @param frequency
     */
    @GetMapping("/createInspectionOrders")
    @Operation(summary = "创建巡查任务-测试", description = "创建巡查任务-测试")
    public void createInspectionOrders(@Parameter(description = "频率", name = "frequency") @RequestParam(name = "frequency", required = true) String frequency,
                                       @Parameter(description = "模板ID", name = "templateId") @RequestParam(name = "templateId", required = true) String templateId) {
        service.createInspectionOrders(frequency, templateId);
    }

    //根据企业id查询巡检工单
    @GetMapping("/queryInspectionOrderByOrgId")
    @Operation(summary = "根据企业id查询巡检工单", description = "根据企业id查询巡检工单")
    public ResponseResult<List<InspectionOrder>> queryInspectionOrderByOrgId(@Parameter(description = "企业ID", name = "orgId") @RequestParam(name = "orgId", required = true) String orgId) {
        return service.queryInspectionOrderByOrgId(orgId);
    }

    //根据客户id查询巡检工单数量
    @GetMapping("/queryInspectionOrderCountByCustomerId")
    @Operation(summary = "根据客户id查询巡检工单数量", description = "根据客户id查询巡检工单数量")
    public ResponseResult<Long> queryInspectionOrderCountByCustomerId(@Parameter(description = "orgId", name = "orgId") @RequestParam(name = "orgId", required = true) String orgId) {
        return service.queryInspectionOrderCountByCustomerId(orgId);
    }

}

